package com.wlc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wlc.bo.Lists;
import com.wlc.bo.Root;
import com.wlc.bo.music.MusicBo;
import com.wlc.controller.music.HttpGetConnect;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 王立朝 wanglichao@champion-credit.com
 * @description 音乐控制器
 * @date 2021-08-10 20:47
 */
@RestController
public class MusicController {

    @Autowired
    private MusicBo musicBo;
    /**
     * 音乐地址的连接
     */

    private static final String MUSIC_ADDR_HREF = "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=";

    @GetMapping("/hello")
    public String hello() {
        return "hello word springboot!";
    }

    /**
     * GET---有参测试 (方式一:手动在url后面加上参数)
     *
     * @date 2018年7月13日 下午4:19:23
     */
    @GetMapping("/Test")
    public List<com.wlc.bo.music.Root> list(String musicName) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 参数
        StringBuffer params = new StringBuffer();
        List<String> fileHashList = null;
        List<com.wlc.bo.music.Root> musicList = null;

        try {
            // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("?callback=jQuery1124006980366032059648_1518578518932&");
            params.append("keyword=" + URLEncoder.encode(musicName, "utf-8"));
            params.append("&page=1&pagesize=30&userid=-1&clientver=");
            params.append("&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1518578518934");

        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 创建Get请求
        HttpGet httpGet = new HttpGet("http://songsearch.kugou.com/song_search_v2" + params);
        // 响应模型
        CloseableHttpResponse response = null;

        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                String result = EntityUtils.toString(responseEntity);
                int start = result.indexOf("(") + 1;
                int end = result.lastIndexOf(")");
                result = result.substring(start, end);
                //System.out.println(result);
                // 获取FileHash 集合
                fileHashList = getFileHashList(result);
                // 根据FileHash 查找 音乐文件不为空的集合，并返回到前台
                musicList = getMusicAdd(fileHashList);
                //System.out.println("musicList = " + musicList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发生错误，结果为：" + e.getMessage());
        }

        return musicList;

    }


    /**
     * 根据fileHash 查找音乐播放的地址不为空的文件列表，并返回
     *
     * @return
     */
    private List<com.wlc.bo.music.Root> getMusicAdd(List<String> fileHashList) {
        List<com.wlc.bo.music.Root> list = new ArrayList<>();
        String connect = "";
        for (int i = 0; i < fileHashList.size(); i++) {
            try {
                connect = new HttpGetConnect().connect(MUSIC_ADDR_HREF + fileHashList.get(i), "utf-8");
                //System.out.println(connect);

                com.wlc.bo.music.Root root = JSONObject.parseObject(connect).toJavaObject(com.wlc.bo.music.Root.class);
                //System.out.println(root);
                String play_url = root.getData().getPlay_url();

                play_url.replace("\\/\\/", "");
                if (!"".equals(play_url)) {
                    list.add(root);
                    root.setPlayUrl(play_url);
                    //System.out.println("play_url = " + play_url);
                }

                //String playUrl = json.getJSONObject("data").getString("play_url");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return list;
    }


    /**
     * 查找所有的FileHash 文件
     *
     * @param result
     * @return
     */
    private List<String> getFileHashList(String result) {
        JSON json = (JSON) JSONObject.parse(result);
        Root root = JSON.toJavaObject(json, Root.class);
        List<Lists> lists = root.getData().getLists();
        List<String> fileHashList = lists.stream().map(Lists::getFileHash).collect(Collectors.toList());
        return fileHashList;
    }


}
